package org.sidora.strata.context;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.context.Context;
import org.sidora.core.context.Equality;
import org.sidora.core.context.Equivalence;
import org.sidora.core.context.StratigraphicRelation;
import org.sidora.core.context.Succesion;
import org.sidora.core.util.AbstractInventory;
import org.sidora.core.util.ParameterCollector;
import org.sidora.strata.Storage;


/**
 * Strata properties which displays properties
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class StrataPropertiesTopComponent extends TopComponent {
    
    private static StrataPropertiesTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "StrataPropertiesTopComponent";
    
    private StrataPropertiesTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(StrataPropertiesTopComponent.class, "CTL_StrataPropertiesTopComponent"));
        setToolTipText(NbBundle.getMessage(StrataPropertiesTopComponent.class, "HINT_StrataPropertiesTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldEqual = new javax.swing.JTextField();
        jTextFieldEquivalent = new javax.swing.JTextField();
        jTextFieldNext = new javax.swing.JTextField();
        jTextFieldPrevious = new javax.swing.JTextField();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Equal to:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Equivalent to:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Next to:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Previous to:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "Context is ...");

        jTextFieldEqual.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldEqualFocusLost(evt);
            }
        });
        jTextFieldEqual.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldEqualMouseClicked(evt);
            }
        });

        jTextFieldEquivalent.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldEquivalentFocusLost(evt);
            }
        });
        jTextFieldEquivalent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldEquivalentMouseClicked(evt);
            }
        });

        jTextFieldNext.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldNextFocusLost(evt);
            }
        });
        jTextFieldNext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldNextMouseClicked(evt);
            }
        });

        jTextFieldPrevious.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldPreviousFocusLost(evt);
            }
        });
        jTextFieldPrevious.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldPreviousMouseClicked(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel3)
                    .add(jLabel2)
                    .add(jLabel4)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel5)
                    .add(jTextFieldPrevious, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                    .add(jTextFieldNext, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                    .add(jTextFieldEquivalent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE)
                    .add(jTextFieldEqual, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 141, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(10, 10, 10)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldEqual, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldEquivalent, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldNext, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldPrevious, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jTextFieldPreviousFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldPreviousFocusLost
        savePreviousTo();
        fillPreviousTo();
    }//GEN-LAST:event_jTextFieldPreviousFocusLost
    
    private void jTextFieldNextFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldNextFocusLost
        saveNextTo();
        fillNextTo();
    }//GEN-LAST:event_jTextFieldNextFocusLost
    
    private void jTextFieldEquivalentFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldEquivalentFocusLost
        saveEquivalence();
        fillEquivalence();
    }//GEN-LAST:event_jTextFieldEquivalentFocusLost
    
    private void jTextFieldEqualFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldEqualFocusLost
        saveEqual();
        fillEquals();
    }//GEN-LAST:event_jTextFieldEqualFocusLost
    
    private void jTextFieldPreviousMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldPreviousMouseClicked
        
    }//GEN-LAST:event_jTextFieldPreviousMouseClicked
    
    private void jTextFieldNextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldNextMouseClicked
        
    }//GEN-LAST:event_jTextFieldNextMouseClicked
    
    private void jTextFieldEquivalentMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldEquivalentMouseClicked
        
    }//GEN-LAST:event_jTextFieldEquivalentMouseClicked
    
    private void jTextFieldEqualMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldEqualMouseClicked
                            }//GEN-LAST:event_jTextFieldEqualMouseClicked
    
    private void saveEqual(){
        List<Context> list;
        list = Context.Inventory.getList(jTextFieldEqual.getText().replace(".",""), Storage.getSite());
        
        
        StratigraphicRelation.Inventory.updateEquality(Storage.getContext(),list);
    }
    
    private void saveEquivalence(){
        List<Context> list;
        
        list = Context.Inventory.getList(jTextFieldEquivalent.getText().replace(".",""), Storage.getSite());
        
        StratigraphicRelation.Inventory.updateEquivalence(Storage.getContext(),list);
    }
    
    private void saveNextTo(){
        List<Context> list;
        
        list = Context.Inventory.getList(jTextFieldNext.getText().replace(".",""), Storage.getSite());
        
        StratigraphicRelation.Inventory.updateNextTo(Storage.getContext(),list);
    }
    
    private void savePreviousTo(){
        List<Context> list;
        
        list = Context.Inventory.getList(jTextFieldPrevious.getText().replace(".",""), Storage.getSite());
        
        StratigraphicRelation.Inventory.updatePrevious(Storage.getContext(),list);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextFieldEqual;
    private javax.swing.JTextField jTextFieldEquivalent;
    private javax.swing.JTextField jTextFieldNext;
    private javax.swing.JTextField jTextFieldPrevious;
    // End of variables declaration//GEN-END:variables
    
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized StrataPropertiesTopComponent getDefault() {
        if (instance == null) {
            instance = new StrataPropertiesTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the StrataPropertiesTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized StrataPropertiesTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find StrataProperties component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof StrataPropertiesTopComponent) {
            return (StrataPropertiesTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        // TODO add custom code on component closing
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return StrataPropertiesTopComponent.getDefault();
        }
    }
    
    
    
    public void fillEquals(){
        if (Storage.getContext() == null)
            return;
        
        String str = "";
        Equality equ;
        List<Equality> equals = StratigraphicRelation.Inventory.getEqualTo(Storage.getContext());
        
        Iterator<Equality> iter2 = equals.iterator();
        
        while (iter2.hasNext()){
            equ = (Equality)iter2.next();
            
            if (equ.getA() == Storage.getContext())
                str += equ.getB().toSmallString() + ", ";
            if (equ.getB() == Storage.getContext())
                str += equ.getA().toSmallString() + ", ";
        }
        
        jTextFieldEqual.setText(str);
    }
    
    public void fillEquivalence(){
        if (Storage.getContext() == null)
            return;
        
        String str = "";
        Equivalence equ;
        List<Equivalence> equals = StratigraphicRelation.Inventory.getEquivalentTo(Storage.getContext());
        
        Iterator<Equivalence> iter2 = equals.iterator();
        
        while (iter2.hasNext()){
            equ = (Equivalence)iter2.next();
            
            if (equ.getA() == Storage.getContext())
                str += equ.getB().toSmallString() + ", ";
            if (equ.getB() == Storage.getContext())
                str += equ.getA().toSmallString() + ", ";
        }
        
        jTextFieldEquivalent.setText(str);
    }
    
    public void fillNextTo(){
        if (Storage.getContext() == null)
            return;
        
        String str = "";
        Succesion suc;
        List<Succesion> sucs = StratigraphicRelation.Inventory.getNextTo(Storage.getContext());
        
        Iterator<Succesion> iter2 = sucs.iterator();
        
        while (iter2.hasNext()){
            suc = (Succesion)iter2.next();
            
            if (suc.getA() == Storage.getContext())
                str += suc.getB().toSmallString() + ", ";
            if (suc.getB() == Storage.getContext())
                str += suc.getA().toSmallString() + ", ";
        }
        
        jTextFieldNext.setText(str);
    }
    
    public void fillPreviousTo(){
        if (Storage.getContext() == null)
            return;
        
        String str = "";
        Succesion suc;
        List<Succesion> sucs = StratigraphicRelation.Inventory.getPreviousTo(Storage.getContext());
        
        Iterator<Succesion> iter2 = sucs.iterator();
        
        while (iter2.hasNext()){
            suc = (Succesion)iter2.next();
            
            if (suc.getA() == Storage.getContext())
                str += suc.getB().toSmallString() + ", ";
            if (suc.getB() == Storage.getContext())
                str += suc.getA().toSmallString() + ", ";
        }
        
        jTextFieldPrevious.setText(str);
    }
    
    
}
